import React from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { DragDropContext, Droppable, Draggable, DropResult } from '@hello-pangea/dnd';
import { MoreVertical, Plus, Trash, Search, Folder, FolderOpen } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";

interface Copy {
  id: string;
  title: string;
  pxh: number;
}

interface Topic {
  id: string;
  name: string;
  pxh: number;
  copies: Copy[];
}

interface NotionSidebarProps {
  // 搜索相关
  searchDialogOpen: boolean;
  setSearchDialogOpen: (open: boolean) => void;
  searchTerm: string;
  searchResults: Array<{topic: Topic, copy: Copy}>;
  handleSearch: (term: string) => void;
  
  // 数据状态
  topics: Topic[];
  loading: boolean;
  expandedTopics: Record<string, boolean>;
  selectedItem: {
    type: 'topic' | 'copy';
    topicId: string;
    copyId?: string;
  } | null;
  
  // 事件处理函数
  handleTopicClick: (e: React.MouseEvent, topicId: string) => void;
  handleCopyClick: (e: React.MouseEvent, topicId: string, copyId: string) => void;
  handleTopicAction: (action: string, topicId: string) => void;
  handleCopyAction: (action: string, copyId: string) => void;
  onDragEnd: (result: DropResult) => void;
}

// 骨架屏组件
const TopicSkeleton = () => (
  <div className="space-y-4">
    {[1, 2, 3].map((i) => (
      <div key={i} className="space-y-2">
        <div className="flex items-center justify-between p-2">
          <div className="flex items-center gap-2">
            <Skeleton className="h-4 w-4" />
            <Skeleton className="h-4 w-24" />
          </div>
          <div className="flex items-center gap-2">
            <Skeleton className="h-4 w-4" />
            <Skeleton className="h-4 w-4" />
          </div>
        </div>
        <div className="pl-4 space-y-2">
          {[1, 2].map((j) => (
            <div key={j} className="flex items-center justify-between p-2">
              <Skeleton className="h-4 w-20" />
              <Skeleton className="h-4 w-4" />
            </div>
          ))}
        </div>
      </div>
    ))}
  </div>
);

export default function NotionSidebar({
  searchDialogOpen,
  setSearchDialogOpen,
  searchTerm,
  searchResults,
  handleSearch,
  topics,
  loading,
  expandedTopics,
  selectedItem,
  handleTopicClick,
  handleCopyClick,
  handleTopicAction,
  handleCopyAction,
  onDragEnd
}: NotionSidebarProps) {
  return (
    <div className="w-64 bg-gray-100 p-4 flex flex-col">
      <div className="flex items-center gap-2 mb-2">
        <Dialog open={searchDialogOpen} onOpenChange={setSearchDialogOpen}>
          <DialogTrigger asChild>
            <div className="flex items-center gap-2 w-full cursor-pointer hover:bg-gray-200 p-2 rounded transition-colors duration-200">
              <Search className="h-4 w-4 text-gray-500" />
              <span className="text-gray-500 text-sm font-medium">搜索文案...</span>
            </div>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle className="text-lg font-semibold">搜索文案</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  className="pl-10 pr-4 py-2 w-full border border-gray-200 rounded-md focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                  placeholder="输入关键词搜索..."
                  value={searchTerm}
                  onChange={(e) => handleSearch(e.target.value)}
                  autoFocus
                />
              </div>
              <div className="max-h-[300px] overflow-y-auto rounded-md">
                {searchResults.map(({ topic, copy }) => (
                  <div
                    key={copy.id}
                    className="flex flex-col gap-1.5 p-3 hover:bg-gray-50 cursor-pointer rounded-md transition-colors duration-200 border-b border-gray-100 last:border-0"
                    onClick={() => {
                      handleCopyClick({ stopPropagation: () => {} } as React.MouseEvent, topic.id, copy.id);
                      setSearchDialogOpen(false);
                    }}
                  >
                    <div className="font-medium text-gray-900">{copy.title}</div>
                    <div className="text-sm text-gray-500 flex items-center gap-2">
                      <Folder className="h-3.5 w-3.5" />
                      {topic.name}
                    </div>
                  </div>
                ))}
                {searchTerm && searchResults.length === 0 && (
                  <div className="text-center text-gray-500 py-8 bg-gray-50 rounded-md">
                    <Search className="h-6 w-6 mx-auto mb-2 text-gray-400" />
                    未找到相关文案
                  </div>
                )}
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="flex justify-between my-4">
        <h2 className="text-lg font-semibold">项目文案管理</h2>
      </div>

      <div className="flex-1 overflow-y-auto">
        {loading ? (
          <TopicSkeleton />
        ) : (
          <DragDropContext onDragEnd={onDragEnd}>
            <Droppable droppableId="topics" type="TOPIC">
              {(provided) => (
                <div {...provided.droppableProps} ref={provided.innerRef}>
                  {topics.map((topic, index) => (
                    <Draggable key={topic.id} draggableId={topic.id} index={index}>
                      {(provided) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                        >
                          <div 
                            className={`flex items-center justify-between p-2 hover:bg-gray-200 rounded cursor-pointer relative ${
                              selectedItem?.type === 'topic' && selectedItem.topicId === topic.id ? 'bg-gray-200' : ''
                            }`}
                            onClick={(e) => handleTopicClick(e, topic.id)}
                            {...provided.dragHandleProps}
                          >
                            <div className="flex items-center gap-2">
                              {expandedTopics[topic.id] ? (
                                <FolderOpen className="h-4 w-4" />
                              ) : (
                                <Folder className="h-4 w-4" />
                              )}
                              <span className='truncate max-w-[160px]'>{topic.name}</span>
                            </div>

                            <div className="flex items-center gap-2 absolute right-2">
                              <span 
                                className='cursor-pointer'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleTopicAction('addCopy', topic.id);
                                }}
                              >
                                <Plus className="h-4 w-4" />
                              </span>
                            </div>
                          </div>
                          
                          {expandedTopics[topic.id] && (
                            <Droppable droppableId={topic.id} type="COPY">
                              {(provided) => (
                                <div
                                  className="pl-4"
                                  {...provided.droppableProps}
                                  ref={provided.innerRef}
                                >
                                  {topic.copies.length === 0 && (
                                    <div className="text-sm text-gray-400 py-2">
                                      将文案拖拽到此处
                                    </div>
                                  )}
                                  {topic.copies.map((copy, index) => (
                                    <Draggable key={copy.id} draggableId={copy.id} index={index}>
                                      {(provided) => (
                                        <div
                                          ref={provided.innerRef}
                                          {...provided.draggableProps}
                                          className={`p-2 hover:bg-gray-200 rounded cursor-pointer flex items-center justify-between group
                                            ${
                                              selectedItem?.type === 'copy' && selectedItem.copyId === copy.id 
                                              ? 'bg-gray-200 ' 
                                              : ''
                                            }`}
                                          {...provided.dragHandleProps}
                                          onClick={(e) => handleCopyClick(e, topic.id, copy.id)}
                                        >
                                          <div className='truncate max-w-[180px]'>
                                            {copy.title}
                                          </div>
                                          <div className='opacity-0 group-hover:opacity-100 transition-opacity'>
                                            <DropdownMenu>
                                              <DropdownMenuTrigger>
                                                <MoreVertical className="h-4 w-4" />
                                              </DropdownMenuTrigger>
                                              <DropdownMenuContent>
                                                <DropdownMenuItem onClick={() => handleCopyAction('delete', copy.id)}>
                                                  <Trash className="mr-2 h-4 w-4" />
                                                  <span>删除</span>
                                                </DropdownMenuItem>
                                              </DropdownMenuContent>
                                            </DropdownMenu>
                                          </div>
                                        </div>
                                      )}
                                    </Draggable>
                                  ))}
                                  {provided.placeholder}
                                </div>
                              )}
                            </Droppable>
                          )}
                        </div>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          </DragDropContext>
        )}
      </div>
    </div>
  );
}